﻿using DevExpress.Utils.Win;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DiaoPaiDaYin;
using DXApplicationTangche.DTO;
using DXApplicationTangche.UC.下单MTO.Service;
using DXApplicationTangche.UC.客户CRM.Service;
using DXApplicationTangche.UC.客户管理;
using DXApplicationTangche.UC.生产计划类型分类管理下单.通用service;
using DXApplicationTangche.UC.订单一览新.订单预览新.model;
using DXApplicationTangche.UC.订单一览新.订单预览新.service;
using DXApplicationTangche.UC.订单一览新.销售确认单;
using DXApplicationTangche.UC.货号管理.service;
using DXApplicationTangche.UC.销售记录.service;
using DXApplicationTangche.UC.门店下单.service;
using mendian;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CustomerOrderCommitDTO = DXApplicationTangche.UC.下单MTO.Service.CustomerOrderCommitDTO;

namespace DXApplicationTangche.UC.下单MTO
{
    public partial class FormMTO订单分录 : DevExpress.XtraEditors.XtraForm
    {
        private String saleType;
        public CustomerPDTO customerPDTO = new CustomerPDTO();
        public OrderCommitDTO返回 orderCommitDTO返回 = new OrderCommitDTO返回();
        //区分套号补货还是团体定制
        public String mobile { get; set; }
        public String getMobile { get; set; }
        private String shopId { get; set; }
        private String shopName { get; set; }
        private String empId { get; set; }
        private String empName { get; set; }
        private String barCode { get; set; }

        private List<SaleOrderDetailRequestDTO> saleOrderDetailRequestDTOList = new List<SaleOrderDetailRequestDTO>();
        private 订单预览新Model model;

        /// <summary>
        /// 套号下单
        /// 参数CUSTOMERTAG——客户套号下单
        /// 参数TAG——补货
        /// </summary>
        /// <param name="saleType"></param>
        public FormMTO订单分录(String saleType)
        {
            InitializeComponent();
            this.saleType = saleType;
            this.config读取店铺();
        }
        private void config读取店铺()
        {
            if (System.IO.File.Exists(@"xml\config店铺.xml"))
            {
                DTO销售表头 dTO店铺 = DealXML.XMLFlieToObject<DTO销售表头>(@"xml\config店铺.xml", Encoding.UTF8);
                this.shopId = dTO店铺.id;
                this.shopName = dTO店铺.name;
                this.searchLookUpEdit店铺.Text = this.shopName;
                this.searchLookUpEdit店铺.Enabled = false;
            }
        }

        /// <summary>
        /// 点右键客户套号下单
        /// </summary>
        /// <param name="saleType"></param>
        /// <param name="mobile"></param>
        public FormMTO订单分录(String saleType,String mobile)
        {
            InitializeComponent();
            this.saleType = saleType;
            this.mobile = mobile;
            this.getTextByMobile(mobile);
            this.textBox手机号查找0.ReadOnly = true;
            this.simpleButton更多客户.Enabled = false;
            this.simpleButton添加客户0.Enabled = false;
        }

        private void FormMTO订单分录_Load(object sender, EventArgs e)
        {
            //控件属性统一写到这
            this.layoutDisplay();
            List < SaleStyleSample > saleStyleSamples = 货号管理Service.getSaleStyleSampleWithDateTime(0, 5000);
            this.searchLookUpEdit选择参考成衣.Properties.DataSource = saleStyleSamples;

        }
        //根据电话号实例化对象并给textbox赋值
        private void getTextByMobile(String getMobile)
        {
            this.getMobile = getMobile;
            this.customerPDTO = CRM客户Service.getCustomerPByMobile(getMobile);
            this.textBox客户姓名.Text = this.customerPDTO.customerName;
            this.textBox联系电话.Text = this.customerPDTO.mobile;
            this.textBox详细地址.Text =
                this.customerPDTO.addressProvince 
                + this.customerPDTO.addressCity
                + this.customerPDTO.addressDistrict
                + this.customerPDTO.addressDetail;
        }
        #region 选择店铺
        private void searchLookUpEdit店铺_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear店铺Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit店铺View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit店铺.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.shopId = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.shopName = this.searchLookUpEdit店铺.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                    if (!System.IO.File.Exists(@"xml\config店铺.xml"))
                    {
                        DealXML.ObjectToXMLFile(new DTO销售表头(this.shopId, this.shopName), @"xml\config店铺.xml", Encoding.UTF8);
                    }
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear店铺Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit店铺.ToolTip = null;
            searchLookUpEdit店铺.EditValue = null;
        }
        private void searchLookUpEdit店铺_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.shopName;
        }
        #endregion
        #region 选销售员
        private void searchLookUpEdit销售员_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear销售员Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit销售员View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit销售员.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    this.empId = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "id").ToString();
                    this.empName = this.searchLookUpEdit销售员.Properties.View.GetRowCellValue(rowHandle, "name").ToString();
                }
            }
        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear销售员Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit销售员.ToolTip = null;
            searchLookUpEdit销售员.EditValue = null;
        }
        private void searchLookUpEdit销售员_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.empName;
        }
        #endregion
        #region 加载图片
        private void 订单信息呈现()
        {
            //显示成衣码查询出内容，无参考意义的进行清空
            this.model.buildCustomerClear().build销售渠道Clear().buildOrderCommit().buildStyleCategoryDTOAndClear().buildClear刺绣();
            //门店定制下单销售渠道赋值
            this.model.build销售渠道("门店下单", "春衫定制");
            
            //款式
            this.gridControl款式.DataSource = this.model.款式DTOs;
            //设计点
            try
            {
                if (this.model.设计点DTOs.Count == 0)
                {
                    this.model.设计点DTOs = 下单相关Service.select接口查设计点(this.model.OrderCommitDTO返回.styleNameCn);
                }
            }
            catch { }
            
        }
        #endregion
        #region 选择参考成衣
        /// <summary>
        /// 绑定清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit选择参考成衣_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn选择参考成衣_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        /// <summary>
        /// 点击选择后的行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit选择参考成衣View_Click(object sender, EventArgs e)
        {
            var a = this.searchLookUpEdit选择参考成衣.Properties.View.GetSelectedRows();
            foreach (int rowHandle in a)
            {
                this.barCode = this.searchLookUpEdit选择参考成衣.Properties.View.GetRowCellValue(rowHandle, "stockInventoryNo").ToString();
            }
            this.textBox扫码.Text = this.barCode;
            OrderCommitDTO返回 orderCommitDTO返回 = MTO订单Service.getOrderCommitDtoByBarcode(barCode);
            this.comboBox尺码.Items.Clear();
            List<String> 尺码 = new List<string>();
            尺码 = MTO订单Service.findSizeCdByStyleNameCn(orderCommitDTO返回.styleNameCn);
            foreach (String str in 尺码)
            {
                this.comboBox尺码.Items.Add(str);
            }
            this.displayText(orderCommitDTO返回);

        }
        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn选择参考成衣_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit选择参考成衣.ToolTip = null;
            searchLookUpEdit选择参考成衣.EditValue = null;
        }
        /// <summary>
        /// 选完之后的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit选择参考成衣_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
                e.DisplayText = this.barCode;
        }
        #endregion

        //添加detail
        private void simpleButton添加_Click(object sender, EventArgs e)
        {
            if ((!String.IsNullOrWhiteSpace(textBox款式名称.Text))
                && (!String.IsNullOrWhiteSpace(comboBox尺码.Text))
                && (!String.IsNullOrWhiteSpace(textBox订单数量.Text))
                && (!String.IsNullOrWhiteSpace(textBox客户姓名.Text))
                && (!String.IsNullOrWhiteSpace(textBox联系电话.Text))
                && (!String.IsNullOrWhiteSpace(textBox详细地址.Text)))
            {
                //saleOrderDetailDTOs是一个list，每次add添加SaleOrderDetailDTO对象
                //SaleOrderDetailDTO由传进来的OrderCommitDTO返回和其他参数组成
                saleOrderDetailRequestDTOList.Add(
                    new SaleOrderDetailRequestDTO(
                    this.barCode,
                    double.Parse(this.textBox订单数量.Text.Trim()),
                    this.richTextBox备注.Text.Trim(),
                    "IGS_GROUP_SIZE-" + this.comboBox尺码.Text.Trim(),
                    new CustomerOrderCommitDTO(customerPDTO),
                    this.textBox款式名称.Text.Trim(),
                    this.textBox面料号.Text.Trim())
                    );
                this.refreshDetails();

                //清空客户信息
                this.clearItem();              
            }
            else
            {
                MessageBox.Show("请补充信息");
            }           
        }

        /// <summary>
        /// 成衣添加后，下方gridcontrol显示刷新
        /// </summary>
        private void refreshDetails()
        {
            this.gridControl订单分录.DataSource = this.saleOrderDetailRequestDTOList;
            this.gridView订单分录.RefreshData();
        }

        /// <summary>
        /// 清空textBox
        /// </summary>
        private void clearItem()
        {
            //判断saleType是补货还是团体定制
            //团体定制，全清空
            if (this.saleType.Equals("客户套号"))
            {
                //this.comboBox尺码.Items.Clear();
                this.textBox订单数量.Clear();
                this.textBox手机号查找0.Clear();
                this.richTextBox备注.Clear();
                this.textBox客户姓名.Clear();
                this.textBox联系电话.Clear();
                this.textBox详细地址.Clear();
            }
            //补货，清空数量尺码
            else if (this.saleType.Equals("套号下单"))
            {
                //this.comboBox尺码.Items.Clear();
                this.textBox订单数量.Clear();
            }
        }
        /// <summary>
        /// 扫码显示款式信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox扫码_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyValue == 13)
            {
                if (!String.IsNullOrWhiteSpace(textBox扫码.Text))
                {
                    OrderCommitDTO返回 orderCommitDTO返回 = MTO订单Service.getOrderCommitDtoByBarcode(textBox扫码.Text.Trim());
                    this.displayText(orderCommitDTO返回);
                    this.textBox扫码.Clear();

                    //显示该款式的尺码组
                    this.comboBox尺码.Items.Clear();
                    List<String> 尺码 = new List<string>();
                    尺码 = MTO订单Service.findSizeCdByStyleNameCn(orderCommitDTO返回.styleNameCn);
                    foreach(String str in 尺码)
                    {
                        this.comboBox尺码.Items.Add(str);
                    }
                }
            }
        }
        /// <summary>
        /// 显示款式信息
        /// </summary>
        /// <param name="orderCommitDTO返回"></param>
        private void displayText(OrderCommitDTO返回 orderCommitDTO返回)
        {
            this.orderCommitDTO返回 = orderCommitDTO返回;
            //扫码从orderCommitDTO传进来款式 面料 价格
            this.barCode = this.textBox扫码.Text.Trim();
            this.textBox款式名称.Text = orderCommitDTO返回.styleNameCn;
            this.textBox面料号.Text = orderCommitDTO返回.materialCode;
            this.textBox面料名称.Text = orderCommitDTO返回.materialNameCn;
            this.textBox成份.Text = orderCommitDTO返回.composition;
            this.textBox建议零售价.Text = orderCommitDTO返回.price.ToString();
            //加载款式图片
            this.model = new 订单预览新Model(this.textBox扫码.Text.Trim(), Enum订单查询.按照水洗标查询订单);
            this.订单信息呈现();
        }
        private void simpleButton提交_Click(object sender, EventArgs e)
        {
            if ((!String.IsNullOrWhiteSpace(dateTimePicker交期.Text))
                && (!String.IsNullOrWhiteSpace(searchLookUpEdit销售员.Text))
                && (!String.IsNullOrWhiteSpace(searchLookUpEdit店铺.Text)))
            {
                //调用Service创建方法，传SaleOrderFacadeDTO
                //SaleOrderFacadeDTO由抬头和detail组成
                //MTO订单Service.createSaleOrder(
                SaleOrderRequestFacadeDTO saleOrderRequestFacadeDTO =
                    new SaleOrderRequestFacadeDTO(
                        new SaleOrderTitleRequstDTO(
                            this.saleType,
                            this.shopId,
                            this.empId,
                            this.dateTimePicker交期.Value
                            ),
                        this.saleOrderDetailRequestDTOList
                    );
                new FormMTO下单提交预览(saleOrderRequestFacadeDTO).ShowDialog();
                this.清空控件();
                //);
                //MessageBox.Show("创建完成");
            }
            else
            {
                MessageBox.Show("请补全信息");
            }
        }
        private void 清空控件()
        {
            this.textBox扫码.Clear();
            this.textBox款式名称.Clear();
            this.searchLookUpEdit选择参考成衣.Text = null;
            this.textBox面料号.Clear();
            this.textBox面料名称.Clear();
            this.textBox成份.Clear();
            this.textBox建议零售价.Clear();
            this.textBox订单数量.Clear();
            this.comboBox尺码.Items.Clear();
            this.saleOrderDetailRequestDTOList.Clear();
            this.gridView订单分录.RefreshData();
        }

        private void simpleButton添加客户0_Click(object sender, EventArgs e)
        {
            new FormMTO添加客户地址().ShowDialog();
        }

        private void textBox手机号查找0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                this.customerPDTO = MTO订单Service.getCustomerPByMobile(this.textBox手机号查找0.Text.Trim());
                this.getTextByMobile(this.customerPDTO.mobile);
                if (String.IsNullOrEmpty(this.customerPDTO.mobile))
                {
                    MessageBox.Show("未创建用户");
                }
            }   
        }

        private void simpleButton更多客户_Click(object sender, EventArgs e)
        {
            new FormMTO客户一览(this.customerPDTO).ShowDialog();
            this.getTextByMobile(this.customerPDTO.mobile);
        }
        /// <summary>
        /// load绑定searchLookUp店铺、销售员
        /// </summary>
        private void layoutDisplay() {
            this.searchLookUpEdit店铺.Properties.DataSource = 销售记录Service.get店铺();
            this.searchLookUpEdit销售员.Properties.DataSource = 销售记录Service.get销售员();

            if (this.saleType.Equals("套号下单"))
            {
                //下单类型是套号补货，写死地址
                this.getTextByMobile("15989118911");
                this.textBox手机号查找0.ReadOnly = true;
                this.simpleButton更多客户.Enabled = false;
                this.simpleButton添加客户0.Enabled = false;
                this.textBox客户姓名.ReadOnly = true;
                this.textBox联系电话.ReadOnly = true;
                this.textBox详细地址.ReadOnly = true;
            }
            else if (this.saleType.Equals("客户套号"))
            {
                //类型是团体套号，清除地址
                //this.getTextByMobile("");
                //this.textBox手机号查找0.ReadOnly = false;
                //this.simpleButton更多客户.Enabled = true;
                //this.simpleButton添加客户0.Enabled = true;
            }
        }
        /// <summary>
        /// 删除选中行，sort为false
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.saleOrderDetailRequestDTOList.RemoveAt(this.gridView订单分录.FocusedRowHandle);
            this.refreshDetails();
        }

        private void simpleButton更多款式_Click(object sender, EventArgs e)
        {
            new FormMTO更多款式(this.orderCommitDTO返回).ShowDialog();
            //this.displayText(this.orderCommitDTO返回);
            this.barCode = orderCommitDTO返回.refBarcode;
            this.textBox款式名称.Text = orderCommitDTO返回.styleNameCn;
            this.textBox面料号.Text = orderCommitDTO返回.materialCode;
            this.textBox面料名称.Text = orderCommitDTO返回.materialNameCn;
            this.textBox成份.Text = orderCommitDTO返回.composition;
            this.textBox建议零售价.Text = orderCommitDTO返回.price.ToString();
            //加载款式图片
            this.model = new 订单预览新Model(this.textBox扫码.Text.Trim(), Enum订单查询.按照水洗标查询订单);
            this.订单信息呈现();
        }

        private void simpleButton查看尺寸表_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(this.textBox款式名称.Text))
            {
                new Form下单时仅查看尺寸表(this.textBox款式名称.Text.Trim()).ShowDialog();
            }
        }
    }
}
